package actions;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import services.UserService;
import t4p.model.User;

/**
 * Servlet implementation class Login
 */
@WebServlet("/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//LLAMAR AL LOGIN DEL USER SERVICE Y DECIDIR SEGUN LA RESPUESTA A QUE PAGINA REDIRECCIONAR
		UserService myUserService =  UserService.getInstace();
		String username = request.getParameter("txtName");
		String password = request.getParameter("txtPassword");
		User myLoggedUser = myUserService.login(username, password);
		if(myLoggedUser != null){
			//EL USUARIO EXISTE, GUARDO EL MISMO EN LA SESION Y REDIRECCIONO A LA HOME PAGE
			HttpSession session = request.getSession(true);
			session.setAttribute("loggedUser", myLoggedUser);
			response.sendRedirect(response.encodeRedirectURL("/aaarrgh/pages/home.jsp") );
		}else{
			//EL USUARIO NO EXISTE, REDIRECCIONO AL LOGIN
			response.sendRedirect(response.encodeRedirectURL("/aaarrgh/index.jsp") );
		}
		
	}
}


